package com.aries.crossgate.modules.sys.service.imp;

import com.aries.crossgate.modules.sys.entity.SysUser;
import com.aries.crossgate.modules.sys.entity.SysUserOnline;
import com.aries.crossgate.modules.sys.service.SysOnlineService;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @description: 
 * @author 李贝留斯
 * @email sunyadongsyd@163.com
 * @date 2018/6/24 23:19
 */
@Service
public class SysOnlineServiceImpl implements SysOnlineService{
	@Autowired
	private SessionDAO sessionDAO;

	@Override
	public List<SysUserOnline> list() {
		List<SysUserOnline> list = new ArrayList<SysUserOnline>();
		Collection<Session> sessions = sessionDAO.getActiveSessions();
		for (Session session : sessions) {
			SysUserOnline sysUserOnline = new SysUserOnline();
			SysUser sysUser = new SysUser();
			SimplePrincipalCollection principalCollection = new SimplePrincipalCollection();
			if (session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) == null) {
				continue;
			} else {
				principalCollection = (SimplePrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
				sysUser = (SysUser) principalCollection.getPrimaryPrincipal();
				sysUserOnline.setUserName(sysUser.getUserName());
			}
			sysUserOnline.setId((String) session.getId());
			sysUserOnline.setHost(session.getHost());
			sysUserOnline.setStartTimestamp(session.getStartTimestamp());
			sysUserOnline.setLastAccessTime(session.getLastAccessTime());
			sysUserOnline.setTimeout(session.getTimeout());
			list.add(sysUserOnline);
		}
		return list;
	}

	@Override
	public Collection<Session> sessionList() {
		return sessionDAO.getActiveSessions();
	}

	@Override
	public boolean forceLogout(String sessionId) {
		Session session = sessionDAO.readSession(sessionId);
		session.setTimeout(0);
		return true;
	}
}
